package dao;

import entity.User;
import utils.DBConnectionUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImplement implements UserDao{
    /**
     * 用户登录
     * @param name 用户名
     * @param password 密码
     * @return
     */
    @Override
    public boolean login(String name, String password) {
        boolean flag = false;
        try {
            DBConnectionUtil.init();

            String sql = "select * from user where name='" + name + "' and password='" + password + "';";
            ResultSet rs = DBConnectionUtil.select(sql);
            if (rs.next()) {
                flag = true;
            }
            DBConnectionUtil.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public boolean register(User user) {
        boolean flag = false;
        DBConnectionUtil.init();
        String sql = "insert into user(name,password,id) values(" + user.getName() + "," + user.getPassword() + "," + user.getId() + ");";
        int i = DBConnectionUtil.update(sql);
        if (i > 0) {
            flag = true;
        }
        DBConnectionUtil.close();
        return flag;
    }

    /**
     * 获取所有用户
     * @return
     */
    @Override
    public List<User> getAllUser() {
        List<User> users = new ArrayList<>();
        DBConnectionUtil.init();
        String sql = "select * from user";
        ResultSet rs = DBConnectionUtil.select(sql);
        try {
            while (rs.next()) {
                String name = rs.getString("name");
                String password = rs.getString("password");
                String id = rs.getString("id");
                User user = new User(name, password, id);
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return users;
    }

    @Override
    public boolean deleteById(String id) {
        return false;
    }

    @Override
    public boolean updateById(String id) {
        return false;
    }
}
